#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import errno
import time
import sys
from StringIO import StringIO


from utils import _exec_shell1, Exp
from names import DevName


class BcacheDev(object):
    def __init__(self, dev):
        self.dev = dev

    def wipe_dev(self):
        cmd = 'wipefs -a %s -f' % self.dev
        try:
            _exec_shell1(cmd, p=True)
        except Exp as e:
            raise Exp(errno.EPERM, "wipefs -a failed\n")
        return True

    def get_cset_uuid(self):
        _exec = "bcache-super-show %s | grep cset.uuid | awk '{print $2}'" % self.dev
        try:
            out, err = _exec_shell1(_exec, p=False)
        except Exp as e:
            raise Exp(errno.EPERM, 'cant get coredev uuid\n')
        return out.strip()

    @staticmethod
    def is_cset_online(cset_uuid):
        return os.path.isdir(os.path.join('/sys/fs/bcache', cset_uuid))

    def create(self):
        pass

    def delete(self):
        pass

    def check(self):
        pass
        cmd = "bcache-super-show %s 2>/dev/null | grep 'cache device'" % self.dev
        try:
            out, err = _exec_shell1(cmd, p=False)
            return True
        except Exp as e:
            return False

    def register(self):
        register_path = '/sys/fs/bcache/register'

        if not os.path.exists(register_path):
            raise Exp(errno.EPERM, "bcache load error\n")

        _exec_register = 'echo %s > /sys/fs/bcache/register' % self.dev
        try:
            _exec_shell1(_exec_register, p=True)
        except Exp as e:
            pass


class CacheDev(BcacheDev):
    def __init__(self, dev):
        super(CacheDev, self).__init__(dev)

    def create(self):
        self.wipe_dev()

        cmd = 'make-bcache -C %s --wipe-bcache' % self.dev
        _exec_shell1(cmd, p=True)

    def check(self):
        cmd = "bcache-super-show %s 2>/dev/null | grep 'cache device'" % self.dev
        try:
            out, err = _exec_shell1(cmd, p=False)
            return True
        except Exp as e:
            return False


class DataDev(BcacheDev):
    def __init__(self, dev):
        super(DataDev, self).__init__(dev)

    def create(self):
        cmd = 'make-bcache -B %s --wipe-bcache' % self.dev
        _exec_shell1(cmd, p=True)

    def check(self):
        devname = DevName(self.dev).name
        check_path = '/sys/block/%s/bcache' % devname
        return os.path.exists(check_path)

    def attatch(self):
        pass

    def clean_lich_meta(self):
        # 8K + 1M
        cmd = 'dd if=/dev/zero of=%s bs=4k count=1026' % self.dev
        _exec_shell1(cmd, p=True)


if __name__ == '__main__':
    cdev = CacheDev('/dev/sdi')
    ddev = CacheDev('/dev/sda')
